package wireguard

import (
	"fmt"
	"net"
	"os"
	"time"

	"golang.zx2c4.com/wireguard/wgctrl"
	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)

func ConfigureInterface(priKey, peerPublicKey, endpoint string) error {

	client, err := wgctrl.New()
	if err != nil {
		return fmt.Errorf("failed to open client: %v", err)
	}
	defer client.Close()

	pri, err := wgtypes.ParseKey(priKey)
	if err != nil {
		return fmt.Errorf("failed to generate private key: %v", err)
	}

	pub, err := wgtypes.ParseKey(peerPublicKey) // Should be generated by the remote peer
	if err != nil {
		return fmt.Errorf("failed to parse public key: %v", err)
	}

	//log.Printf("Public Key [%s]", pri.PublicKey())

	port := 51820
	ka := 20 * time.Second

	conf := wgtypes.Config{
		PrivateKey:   &pri,
		ListenPort:   &port,
		ReplacePeers: true,
		Peers: []wgtypes.PeerConfig{{
			PublicKey:  pub,
			Remove:     false,
			UpdateOnly: false,
			Endpoint: &net.UDPAddr{
				IP:   net.ParseIP(endpoint),
				Port: 51820,
			},
			PersistentKeepaliveInterval: &ka,
			ReplaceAllowedIPs:           true,
			AllowedIPs: []net.IPNet{{
				IP:   net.ParseIP("10.0.0.0"),
				Mask: net.ParseIP("0.0.0.0").DefaultMask(),
			}},
		}},
	}

	if err := client.ConfigureDevice("wg0", conf); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("wg0 doesn't exist [%s]", err)
		}
		return fmt.Errorf("unknown config error: %v", err)
	}
	return nil
}
